-- combat_system.lua
-- 保持原版，修复已在上面的action_system中处理

local CombatSystem = {}
CombatSystem.__index = CombatSystem

function CombatSystem.new(movementSystem, keyboardInput, characterMonitor, actionSystem)
    local instance = {
        movementSystem = movementSystem,
        keyboardInput = keyboardInput,
        characterMonitor = characterMonitor,
        actionSystem = actionSystem,
        
        -- 战斗状态
        currentState = "idle",
        currentWeaponMode = "chi",
        
        -- 攻击输入
        lastJPressed = false,
        
        -- 连击系统
        currentCombo = 0,
        maxComboByMode = {
            chi = 4,
            chui = 3,
            zao = 2
        },
        
        -- 攻击冷却
        attackCooldownTime = 0.1,
        attackCooldownTimer = 0,
        
        -- 连击控制
        _comboLocked = false,
        _comboInputQueued = false,
        _queuedComboNumber = 0,
        
        -- 输入缓冲
        _inputBuffer = false,
        _bufferTimer = 0,
        _bufferDuration = 0.2,
        
        -- 调试模式
        debugMode = true
    }
    
    return setmetatable(instance, CombatSystem)
end

-- 更新战斗系统
function CombatSystem:update(dt)
    -- 更新武器模式
    local currentMode = self.characterMonitor:getCurrentMode()
    if currentMode == "chi" then
        self.currentWeaponMode = "chi"
    elseif currentMode == "chui" then
        self.currentWeaponMode = "chui"
    elseif currentMode == "zao" then
        self.currentWeaponMode = "zao"
    end
    
    -- 更新计时器
    self:updateTimers(dt)
    
    -- 处理攻击输入
    self:handleAttackInput()
    
    -- 更新按键状态
    self.lastJPressed = self.keyboardInput:isKeyPressed("J")
end

-- 更新计时器
function CombatSystem:updateTimers(dt)
    if self.attackCooldownTimer > 0 then
        self.attackCooldownTimer = math.max(0, self.attackCooldownTimer - dt)
    end
    
    if self._bufferTimer > 0 then
        self._bufferTimer = math.max(0, self._bufferTimer - dt)
        if self._bufferTimer <= 0 then
            self._inputBuffer = false
        end
    end
end

-- 处理攻击输入
function CombatSystem:handleAttackInput()
    local jPressed = self.keyboardInput:isKeyPressed("J")
    local jJustPressed = jPressed and not self.lastJPressed
    
    if not jJustPressed then 
        return 
    end
    
    if self.debugMode then
        print("J键按下，当前状态: " .. self.currentState .. 
              ", 当前连击: " .. self.currentCombo)
    end
    
    -- 攻击冷却检查
    if self.attackCooldownTimer > 0 then
        if self.debugMode then
            print("攻击冷却中: " .. string.format("%.3f", self.attackCooldownTimer))
        end
        return
    end
    
    -- 检查连击锁定
    if self._comboLocked then
        if self.debugMode then
            print("连击被锁定，忽略输入")
        end
        return
    end
    
    if self.currentState == "idle" then
        -- 空闲状态，开始第一段攻击
        if self.debugMode then
            print("开始第一段攻击")
        end
        self:startAttack(1)
    elseif self.currentState == "attacking" then
        -- 攻击状态中，检查连击
        local nextCombo = self.currentCombo + 1
        local maxCombo = self.maxComboByMode[self.currentWeaponMode] or 4
        
        if nextCombo <= maxCombo then
            -- 尝试通过动作系统接收连击输入
            if self.actionSystem and self.actionSystem:receiveComboInput(nextCombo) then
                -- 动作系统已接收并排队
                self._comboInputQueued = true
                self._queuedComboNumber = nextCombo
                self._comboLocked = true
                
                if self.debugMode then
                    print("✓ 连击输入已排队: 第 " .. nextCombo .. " 段")
                end
            else
                -- 不在连击窗口内，存入缓冲区
                self._inputBuffer = true
                self._bufferTimer = self._bufferDuration
                
                if self.debugMode then
                    print("不在连击窗口内，输入存入缓冲区")
                end
            end
        else
            if self.debugMode then
                print("已达到最大连击数")
            end
        end
    end
    
    -- 检查缓冲输入
    if self._inputBuffer and self.currentState == "attacking" then
        local nextCombo = self.currentCombo + 1
        local maxCombo = self.maxComboByMode[self.currentWeaponMode] or 4
        
        if nextCombo <= maxCombo then
            if self.actionSystem and self.actionSystem:receiveComboInput(nextCombo) then
                self._comboInputQueued = true
                self._queuedComboNumber = nextCombo
                self._comboLocked = true
                self._inputBuffer = false
                self._bufferTimer = 0
                
                if self.debugMode then
                    print("✓ 执行缓冲输入，排队第 " .. nextCombo .. " 段攻击")
                end
            end
        end
    end
end

-- 执行排队攻击
function CombatSystem:executeQueuedAttack(comboNumber)
    if self.debugMode then
        print("执行排队攻击: 第 " .. comboNumber .. " 段")
    end
    
    -- 动作系统已经处理了动画播放，我们只需要更新状态
    self.currentCombo = comboNumber
    self.currentState = "attacking"
    self._comboInputQueued = false
    self._queuedComboNumber = 0
    self._comboLocked = false
    
    if self.debugMode then
        print("战斗系统状态更新为第 " .. comboNumber .. " 段攻击")
    end
end

-- 开始攻击
function CombatSystem:startAttack(comboNumber)
    local weaponMode = self.currentWeaponMode
    local maxCombo = self.maxComboByMode[weaponMode] or 4
    
    if comboNumber > maxCombo then
        if self.debugMode then
            print("连击数超出最大值，返回空闲")
        end
        self:returnToIdle()
        return
    end
    
    -- 重置状态
    self._comboInputQueued = false
    self._queuedComboNumber = 0
    self._comboLocked = false
    self._inputBuffer = false
    self._bufferTimer = 0
    
    -- 更新状态
    self.currentCombo = comboNumber
    self.currentState = "attacking"
    
    -- 设置攻击冷却
    self.attackCooldownTimer = self.attackCooldownTime
    
    if self.debugMode then
        print("开始第 " .. comboNumber .. " 段攻击，武器模式: " .. weaponMode)
    end
    
    -- 播放攻击动画
    self:playAttackAnimation(comboNumber)
end

-- 播放攻击动画
function CombatSystem:playAttackAnimation(comboNumber)
    if self.actionSystem then
        local success = self.actionSystem:playAttackAnimation(self.currentWeaponMode, comboNumber)
        
        if not success then
            if self.debugMode then
                print("播放攻击动画失败，返回空闲状态")
            end
            self:returnToIdle()
        end
    else
        if self.debugMode then
            print("动作系统不存在，无法播放攻击动画")
        end
        self:returnToIdle()
    end
end

-- 攻击动画完成回调
function CombatSystem:onAttackAnimationComplete()
    if self.debugMode then
        print("攻击动画完成回调，当前连击: " .. self.currentCombo)
    end
    
    if self.currentState == "attacking" then
        -- 检查是否有排队的连击
        if self._comboInputQueued and self._queuedComboNumber > 0 then
            local nextCombo = self._queuedComboNumber
            self._comboInputQueued = false
            self._queuedComboNumber = 0
            
            if self.debugMode then
                print("执行排队的连击: 第 " .. nextCombo .. " 段")
            end
            
            -- 通知动作系统执行排队攻击，它会通过_playQueuedAttack处理
            -- 我们只需要更新战斗系统状态
            self.currentCombo = nextCombo
            self._comboLocked = false
            
            if self.debugMode then
                print("战斗系统状态更新为第 " .. nextCombo .. " 段攻击")
            end
        else
            -- 检查缓冲输入
            if self._inputBuffer then
                local nextCombo = self.currentCombo + 1
                local maxCombo = self.maxComboByMode[self.currentWeaponMode] or 4
                
                if nextCombo <= maxCombo then
                    if self.debugMode then
                        print("执行缓冲的连击输入，开始第 " .. nextCombo .. " 段攻击")
                    end
                    self._inputBuffer = false
                    self._bufferTimer = 0
                    self:startAttack(nextCombo)
                    return
                end
            end
            
            -- 没有排队连击，返回空闲
            if self.debugMode then
                print("没有排队连击，返回空闲状态")
            end
            self:returnToIdle()
        end
    else
        self:returnToIdle()
    end
end

-- 返回到空闲状态
function CombatSystem:returnToIdle()
    if self.debugMode and self.currentState ~= "idle" then
        print("返回空闲状态，之前状态: " .. self.currentState)
    end
    
    self.currentCombo = 0
    self.currentState = "idle"
    self._comboLocked = false
    self._comboInputQueued = false
    self._queuedComboNumber = 0
    self._inputBuffer = false
    self._bufferTimer = 0
    
    if self.debugMode then
        print("返回空闲状态完成")
    end
end

-- 获取战斗系统状态
function CombatSystem:getStatus()
    return {
        state = self.currentState,
        weaponMode = self.currentWeaponMode,
        currentCombo = self.currentCombo,
        maxCombo = self.maxComboByMode[self.currentWeaponMode] or 0,
        attackCooldownRemaining = self.attackCooldownTimer,
        comboInputQueued = self._comboInputQueued,
        queuedComboNumber = self._queuedComboNumber,
        comboLocked = self._comboLocked,
        inputBuffered = self._inputBuffer,
        bufferRemaining = self._bufferTimer
    }
end

-- 清理资源
function CombatSystem:cleanup()
    self:returnToIdle()
end

return CombatSystem